﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SSharp.Core.Util {
	/// <summary>
	/// Extends the Dictionary class to automatically generate members when they don't already exist.
	/// Can be used to memoize a function quite easily.
	/// </summary>
	public class Cache<K, V> : Dictionary<K, V> {
		private Func<K, V> getter;

		public Cache(Func<K, V> getter) {
			this.getter = getter;
		}

		public new V this[K key] {
			get {
				if (ContainsKey(key)) {
					return base[key];
				} else {
					V result = getter(key);
					base[key] = result;
					return result;
				}
			}
			set {
				base[key] = value;
			}
		}
	}
}
